<?php

class PaperController extends Zend_Controller_Action 
{
    protected $_model;
	protected $user;
	public function preDispatch(){
		if (Zend_Auth::getInstance()->hasIdentity()) {
			$this->user = Zend_Auth::getInstance()->getIdentity();
            if(!is_object($this->user)){
			    $request = $this->getRequest();
                $c = $request->getControllerName();
                $a = $request->getActionName();
                $loginUrl = $this->view->lang . '/login/index/?returnUrl=';
                $returnUrl = $this->view->url(array('controller' => $c, 'action' => $a), 'default', true);            
                $loginUrl .= $returnUrl;
			    $this->_helper->redirector->gotoUrl($loginUrl);
		    }
		}else{
            $request = $this->getRequest();
            $c = $request->getControllerName();
            $a = $request->getActionName();
            $loginUrl = $this->view->lang . '/login/index/?returnUrl=';
            $returnUrl = $this->view->url(array('controller' => $c, 'action' => $a), 'default', true);            
            $loginUrl .= $returnUrl;
			$this->_helper->redirector->gotoUrl($loginUrl);
         /*   $request = $this->getRequest();
            $request->setActionName('index');
            $request->setControllerName('login');*/
		}
	}
	public function init()
    {
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('view', 'html')
                    ->addActionContext('comment', 'html')                    
                    ->initContext();
    }
    public function indexAction(){
        $this->view->navTitle = $this->view->translate('submition');
    	$request = $this->getRequest();        
		if($request->isPost()){
			$model = $this->getPaper();
			$paper = array();
			$paper_id = $request->getParam('paper_id');
			if(isset($paper_id) && $paper_id != -1){
				$p = $model->fetchEntry($paper_id);
				$p->isActive = 0;
				$p->save();
				$paper['parent_id'] = $paper_id;
			}
            $c = $this->getActiveConference();
			$paper['participant_id'] = $this->user->id;
			$paper['isCurrent'] = 1;
			$paper['conference_id'] = $c->id;
			$paper['area_id'] = $request->getParam('area_id');
			$paper['category_id'] = $request->getParam('category_id');
			$paper['status_id'] = 1; //TODO check default status
			$paper['isActive'] = 1;
            $paper['isAccepted'] = 0;
			$paper['authors'] = $request->getParam('authors');
			$paper['abstract'] = $request->getParam('abstract');
			$paper['email'] = $request->getParam('email');
			$paper['title'] = $request->getParam('title');
			$paper['isAssigned'] = 0;
			$area = $request->getParam('area');
			$file_name = 'temp';
			$ext1 = substr($_FILES['file_pdf']['name'], strrpos($_FILES['file_pdf']['name'], '.'));
			$ext2 = substr($_FILES['file_doc']['name'], strrpos($_FILES['file_doc']['name'], '.'));
			$paper['file_pdf'] = $file_name . $ext1;
			$paper['file_doc'] = $file_name . $ext2;
			$file1 = false;
			$file2 = false;
			if (is_uploaded_file($_FILES['file_pdf']['tmp_name'])) {				
				move_uploaded_file($_FILES['file_pdf']['tmp_name'], PDF_FILES_PATH . $paper['file_pdf']);
				$file1 = true;
			}
			if (is_uploaded_file($_FILES['file_doc']['tmp_name'])) {				
				move_uploaded_file($_FILES['file_doc']['tmp_name'], DOC_FILES_PATH . $paper['file_doc']);
				$file2 = true;
			}
			$paper['id'] = $model->save($paper);
			$old_pdf = PDF_FILES_PATH . $paper['file_pdf'];
			$old_doc = DOC_FILES_PATH . $paper['file_doc'];
			if($file1){
				$paper['file_pdf'] = $area. $paper['id'] . $ext1;
				rename($old_pdf, PDF_FILES_PATH . $paper['file_pdf']);
			}else{
				$paper['file_pdf'] = '';
			}
			if($file2){
				$paper['file_doc'] = $area . $paper['id'] . $ext2;
				rename($old_doc, DOC_FILES_PATH . $paper['file_doc']);
			}else{
				$paper['file_doc'] = '';
			}
			$model->save($paper);
			die();
		}
    }
    public function uploadAction(){
   		$this->view->navTitle = $this->view->translate('submition');
        $c = $this->getActiveConference();
        if(isset($c)){
            $date = new Zend_Date($c->date_submition, Zend_Date::ISO_8601);   
            $now = new Zend_Date();            
            if($now->isEarlier($date)){
                $this->canUpload = true;                
            }else{
                $this->canUpload = false;
                $this->_forward('index', 'paper');
            }
        }            
		$this->view->email = $this->user->email;
		$this->view->name = $this->user->first_name . ' ' . $this->user->last_name;
    }
	
	public function downloadAction(){
		$request = $this->getRequest();
		if($request->isGet()){
			$id = $request->getParam('id');
			$ft = $request->getParam('ft');
			if(is_numeric($id)){
				$paper = $this->getPaper();
				$can = $paper->checkForDownload($id, $this->user->id);
				if($can >= 0){
					if($can > 0){
						$a = $this->getAssignment();
						$assignment = $a->fetchEntry($can);
						$assignment->date_downloaded = date('Y-m-d H:i:s', time());
						$assignment->save();
					}
					$p = $paper->fetchEntry($id);
					if($ft == 'doc'){
						$fn = $p->file_doc;
						$file_path = DOC_FILES_PATH . $p->file_doc;
					}
					if($ft == 'pdf'){
						$fn = $p->file_pdf;
						$file_path = PDF_FILES_PATH . $p->file_pdf;
					}
					header('Content-type: force-download');
					header("Content-Transfer-Encoding: Binary");
					header("Content-length: ".filesize($file_path));
					header("Content-Disposition: attachment; filename=".$fn);
					readfile($file_path); 
					die();
				}
			}
			echo "Invalid request";
		}
	}
	public function postedAction(){
        $this->view->navTitle = $this->view->translate('posted');
	}
	
    public function getpostedAction()
    {
    	$id = $this->user->id;
       $model = $this->getPaper();
      $request = $this->getRequest();
    	$callback = $request->getParam('callback');
       $papers = $model->getByParticipantId($id);
      $count = count($papers);
        $json = array();
        $json['totalCount'] = $count;
        $json['papers'] = $papers;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
    }
	
	public function getpaperAction(){
		$model = $this->getPaper();
		$request = $this->getRequest();
		$paper_id = $request->getParam('id');
    	$callback = $request->getParam('callback');
        $p = $model->fetchEntry($paper_id);
		$papers = array();
		$papers[0] = $p->toArray();
		$count = count($papers);
        $json = array();
        $json['totalCount'] = $count;
        $json['papers'] = $papers;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}
 	
    protected function getPaper()
    {
        if (null === $this->_model) {
            require_once APPLICATION_PATH . '/models/Paper.php';
            $this->_model = new Model_Paper();
        }
        return $this->_model;
    }
	private function getCategories(){
		require_once APPLICATION_PATH . '/models/Category.php';
      	$model = new Model_Category();
      	return $model->fetchEntries();
    } 
	private function getReview(){
		require_once APPLICATION_PATH . '/models/Review.php';
      	$model = new Model_Review();
      	return $model;
    }     
	private function getAssignment(){
		require_once APPLICATION_PATH . '/models/Assignment.php';
      	$model = new Model_Assignment();
      	return $model;
    }
    private function getAreas(){
		require_once APPLICATION_PATH . '/models/Area.php';
      	$model = new Model_Area();
      	return $model->fetchEntries();
    } 
    private function getActiveConference(){
		require_once APPLICATION_PATH . '/models/Conference.php';
      	$model = new Model_Conference();
      	return $model->getActive();
    }   
}